//
//  DiaryForDayController.swift
//  MoodDiary
//
//  Created by 杨鸿 on 2021/12/20.
//

import UIKit
import MJExtension
import SVProgressHUD

class DiaryForDayController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var titleBtn: UIButton?
    var monthDic: [String : [[String : Any]]] = [:]
    var mYear = ""
    var mMonth = ""
    var mDay = ""
    
    var tempEditIndex:Int = -1
    // 历史数据
    var hisDic: [String: [String: [[String: Any]]]] = [:]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.backgroundColor = .white
        
        titleBtn = UIButton(type: .custom)
        titleBtn?.bounds = CGRect(x: 0, y: 0, width: 200.0, height: 30.0)
        titleBtn?.setTitle("\(mYear)年\(mMonth)月\(mDay)日", for: .normal)
        titleBtn?.setTitleColor(.black, for: .normal)
        titleBtn?.titleLabel?.font = .systemFont(ofSize: 17.0, weight: .medium)
        navigationItem.titleView = titleBtn
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 185
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(UINib(nibName: "DiarySectionOCTableViewCell", bundle: .main), forCellReuseIdentifier: "DiarySectionOCTableViewCell")
        tableView.reloadData()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "添加日记小")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(addAction))
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "返回"), style: .plain, target: self, action: #selector(closeAction))
        
        // 需要处理一下arr为空
        monthDic = monthDic.filter({ $0.value.count != 0})
    }
    
    @objc func addAction() {
        var diaryModel = DiaryModel()
        var timeStr = "\(mYear)" + "-" + "\(mMonth)" + "-" + "\(mDay)"
        timeStr += " "
        timeStr += NSString.getHourAndMinute(NSString.currentTimeStamp())
        diaryModel.timeStampStr = NSString.convertTime(toTimeStamp: timeStr)
        diaryModel.weatherStr = "晴天"
        
        let vc = AddMoodViewController()
        vc.dayStr = "这天"
        vc.diaryModel = diaryModel
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func closeAction() {
        dismiss(animated: true, completion: nil)
    }
}

// MARK: - UITableViewDelegate & UITableViewDataSource

extension DiaryForDayController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return monthDic[String(format: "%02ld", Int(mDay)!)]!.count
    }
        
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "DiarySectionOCTableViewCell", for: indexPath)
        if let mCell = cell as? DiarySectionOCTableViewCell {
            if let data = monthDic[String(format: "%02ld", Int(mDay)!)]?[indexPath.row] {
                mCell.dayArray = [data]
                mCell.delegate = self
                mCell.currentPart = indexPath.row
            }
        }
       return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let reason = monthDic[String(format: "%02ld", Int(mDay)!)]?[indexPath.row]["reasonDetailStr"] as? NSString {
            if reason.length > 0 {
                
                var extraHeight: CGFloat = 25.0
                if #available(iOS 15.0, *) {
                    extraHeight = 50.0
                }
                
                if reason.contains("isAttributedString"){
                    
                    let timeStamp:String = monthDic[String(format: "%02ld", Int(mDay)!)]?[indexPath.row]["timeStampStr"] as! String
                    
                    let fileManager = FileManager.default
                    let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
                    
                    let attriPath = docPath + "/" + timeStamp + ".txt"
                    
                    if fileManager.fileExists(atPath: attriPath){
                        
                        if let data = fileManager.contents(atPath: attriPath) {
                            
                            let attr:NSAttributedString = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSAttributedString
                            //若列表需要显示图片，打开下列高度计算代码
                            let mutableAttr = NSMutableAttributedString.init(attributedString: attr)

                            attr.enumerateAttributes(in: NSMakeRange(0, attr.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, range, stop) in

                                if let textAtt:NSTextAttachment = object[NSAttributedString.Key(rawValue: "NSAttachment")] as? NSTextAttachment {

//                                    let tempImage:UIImage = textAtt.image!;
//
//                                    let scale = tempImage.size.width / tempImage.size.height;
//                                    var height = 80.0;
//                                    var width = scale * height;
//                                    if (scale > 1){
//                                        width = 80;
//                                        height = width/scale;
//                                    }
//
//                                    textAtt.bounds = CGRect(x: 0, y: 0, width: width, height: height)
//                                    mutableAttr.replaceCharacters(in: range, with: NSAttributedString.init(attachment: textAtt))
                                    mutableAttr.replaceCharacters(in: range, with: NSAttributedString.init(string: ""))
                                }

                            }
//
//                            let height = mutableAttr.boundingRect(with: CGSize(width: AppWidth - 75.0 - 22.0 - 30.0*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size.height + extraHeight

                            let tempStr = mutableAttr.string.trimmingCharacters(in: NSCharacterSet.newlines)
                            let height = tempStr.boundingRect(with: CGSize(width: AppWidth - 75.0 - 22.0 - 30.0*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)], context: nil).size.height + extraHeight
                            return 140.0 + height
                        }
                        
                    }
                    
                }else{
                    
                    let height = reason.boundingRect(with: CGSize(width: AppWidth - 75.0 - 22.0 - 30.0*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0)], context: nil).size.height + extraHeight
                    return 140.0 + height
                }
            }
        }
        return 140.0
    }

}

extension DiaryForDayController {
    
    func colorWithType(_ typeStr: String) -> UIColor {
        if (typeStr == "开心") {
            return UIColor.hexColor(hex: "#FDB851")
        } else if (typeStr == "惊喜") {
            return UIColor.hexColor(hex: "#A7D16F")
        } else if (typeStr == "得意") {
            return UIColor.hexColor(hex: "#35BD5E")
        } else if (typeStr == "甜蜜") {
            return UIColor.hexColor(hex: "#FF804B")
        } else if (typeStr == "暖心") {
            return UIColor.hexColor(hex: "#E785A7")
        } else if (typeStr == "充实") {
            return UIColor.hexColor(hex: "#FDB851")
        } else if (typeStr == "平静") {
            return UIColor.hexColor(hex: "#F49CBA")
        } else if (typeStr == "无聊") {
            return UIColor.hexColor(hex: "#848CB4")
        } else if (typeStr == "尴尬") {
            return UIColor.hexColor(hex: "#FDB851")
        } else if (typeStr == "不安") {
            return UIColor.hexColor(hex: "#848CB4")
        } else if (typeStr == "伤心") {
            return UIColor.hexColor(hex: "#97C3DD")
        } else if (typeStr == "生气") {
            return UIColor.hexColor(hex: "#F18757")
        } else if (typeStr == "流泪") {
            return UIColor.hexColor(hex: "#6FB1ED")
        } else if (typeStr == "分裂") {
            return UIColor.hexColor(hex: "#FDB851")
        } else if (typeStr == "疲惫") {
            return UIColor.hexColor(hex: "#97C3DD")
        } else if (typeStr == "孤独") {
            return UIColor.hexColor(hex: "#97C3DD")
        } else if (typeStr == "梦境") {
            return UIColor.hexColor(hex: "#848CB4")
        } else if (typeStr == "不好描述") {
            return UIColor.hexColor(hex: "#A7D16F")
        } else {
            return UIColor.hexColor(hex: "#A7D16F")
        }
    }
}

extension DiaryForDayController: DiarySectionOCTableViewCellDelegate {
    
    func diarySectionOCTableViewCellSelectPart(_ currentPart: Int, andSection currentSection: Int, andRow currentRow: Int, andDeletedDiaryStamp timeStampStr: String) {
        showEditAlert(currentPart)
    }
    
    func checkDetailDiary(withData dict: [AnyHashable : Any], index editIndex: Int) {
        
        tempEditIndex = editIndex
        let detailVC = AddDiaryContentViewController.init()
        detailVC.diaryDict = (dict as NSDictionary) as? Dictionary<String, Any>
        detailVC.pageType = .typeDetail
        detailVC.delegate = self
        detailVC.editIndex = editIndex
        navigationController?.pushViewController(detailVC, animated: true)
    }
    
    func showEditAlert(_ index: Int) {
        let alertVC = UIAlertController(title: "提示", message: "请选择您要进行的操作", preferredStyle: UIAlertController.Style.actionSheet)
        alertVC.addAction(UIAlertAction(title: "编辑", style: UIAlertAction.Style.default, handler: { [weak self] action in
            // 编辑
            self?.jumpToEdit(index)
        }))
        
        alertVC.addAction(UIAlertAction(title: "删除", style: UIAlertAction.Style.default, handler: { [weak self] action in
            // 删除
            self?.deleteRowAlert(index)
        }))
        
        alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { action in
            // 取消
        }))
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    
    func jumpToEdit(_ index: Int) {
        
        tempEditIndex = index
        guard let dayDic = monthDic[String(format: "%02ld", Int(mDay)!)]?[index] else { return }
        let vc = DiaryEditViewController()
        vc.dic = dayDic
        vc.delegate = self
        vc.editIndex = index
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func deleteRowAlert(_ index: Int) {
        self.presentedViewController?.dismiss(animated: true, completion: nil)
        let alertVC = UIAlertController(title: "提示", message: "确定删除这条数据?", preferredStyle: UIAlertController.Style.actionSheet)
        alertVC.addAction(UIAlertAction(title: "删除", style: UIAlertAction.Style.default, handler: { [weak self] action in
            // 删除
            self?.deleteRow(index)
        }))
        
        alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.destructive, handler: { action in
            // 取消
        }))
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func deleteRow(_ index: Int) {
        let fileManager = FileManager.default
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let folderPath = docPath + "/" + mYear + "/"
        var monthSavePath = String(format: "%02ld.plist", Int(mMonth)!)

        monthSavePath = folderPath + monthSavePath
        guard fileManager.fileExists(atPath: folderPath) == true else {
            // 没找到历史数据
            return
        }
        let willRemoveDict = monthDic // 缓存一下
        monthDic[String(format: "%02ld", Int(mDay)!)]?.remove(at: index)
        (monthDic as NSDictionary).write(toFile: monthSavePath, atomically: true)
        self.tableView.reloadData()
        
        // 天气
        let weatherPath = docPath + "/weather.plist"
        var weatherArr = NSMutableArray(contentsOfFile: weatherPath) as? [[String: Any]]
        weatherArr = weatherArr?.filter({ dict in
            return dict["timeStamp"] as? String != willRemoveDict[mDay]?[index]["timeStampStr"] as? String
        })
        
        if let weatherArrForWrite = weatherArr as? NSMutableArray {
            weatherArrForWrite.write(toFile: weatherPath, atomically: true)
        } else {
            NSMutableArray().write(toFile: weatherPath, atomically: true)
        }

        // 心情
        let moodPath = docPath + "/mood.plist"
        var moodArr = NSMutableArray(contentsOfFile: moodPath) as? [[String: Any]]
        moodArr = moodArr?.filter({ dict in
            return dict["timeStamp"] as? String != willRemoveDict[mDay]?[index]["timeStampStr"] as? String
        })
        if let moodArrForWrite = moodArr as? NSMutableArray {
            moodArrForWrite.write(toFile: moodPath, atomically: true)
        }else {
            NSMutableArray().write(toFile: moodPath, atomically: true)
        }
        
        // 活动
        let activityPath = docPath + "/activity.plist"
        var activityArr = NSMutableArray(contentsOfFile: activityPath) as? [[String: Any]]
        activityArr = activityArr?.filter({ dict in
            return dict["timeStamp"] as? String != willRemoveDict[mDay]?[index]["timeStampStr"] as? String
        })

        if let activityArrForWrite = activityArr as? NSMutableArray {
            activityArrForWrite.write(toFile: activityPath, atomically: true)
        }else {
            NSMutableArray().write(toFile: activityPath, atomically: true)
        }
        
        // 发送保存通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "editDiaryCompleted"), object: nil)
    }
}

extension DiaryForDayController: AddDiaryContentViewControllerDelegate {
    
    func diaryDelete(index: Int, timeStamp: String) {
        
        self.deleteRow(index)
    }
    
    func attributeEditDone(dict: NSDictionary?, attriStr: NSAttributedString?) {
        
        self.diaryEditDone(dic: dict, editIndex: tempEditIndex, attriStr: attriStr)
    }
    
}
extension DiaryForDayController: DiaryEditViewControllerDelegate {
    
    func diaryEditDone(dic: NSDictionary?, editIndex: Int, attriStr: NSAttributedString?) {

        // 编辑完成 刷新页面
        let fileManager = FileManager.default
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let folderPath = docPath + "/" + NSString.getYear((dic?["timeStampStr"] as? String)!)  + "/"
        var monthSavePath = String(format: "%02ld.plist", Int(NSString.getMonth((dic?["timeStampStr"] as? String)!))!)
//        if NSString.currentYear() == mYear {
//            monthSavePath = String(format: "%02ld.plist", 24 - Int(mMonth)!)
//        } else {
//            monthSavePath = String(format: "%02ld.plist", 12 - Int(mMonth)!)
//        }
        monthSavePath = folderPath + monthSavePath
        guard fileManager.fileExists(atPath: folderPath) == true else {
            // 没找到历史数据
            return
        }
        
        monthDic[String(format: "%02ld", Int(mDay)!)]?[editIndex] = dic as! [String : Any]
        (monthDic as NSDictionary).write(toFile: monthSavePath, atomically: true)
        self.tableView.reloadData()
        
        //富文本储存
//        NSString *attrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
//        NSString *attrPath = [attrDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",dic[@"timeStampStr"]]];
//        NSData *attrData = [NSKeyedArchiver archivedDataWithRootObject:attriStr];
//        [attrData writeToFile:attrPath atomically:YES];
////
        //富文本储存
        var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        url?.appendPathComponent((dic?["timeStampStr"] as? String)! + ".txt")
        let attriStrData = NSKeyedArchiver.archivedData(withRootObject: attriStr as Any)
        do {
            try attriStrData.write(to: url!)
        } catch {
            print(error)
        }
        
        // 天气
        let weatherPath = docPath + "/weather.plist"
        if let weatherArr = NSMutableArray(contentsOfFile: weatherPath) {
            for i in 0..<weatherArr.count {
                if let dic2 = weatherArr[i] as? NSDictionary, let t1 = dic2["timeStamp"] as? String, let t2 = dic?["timeStampStr"] as? String {
                    if t1 == t2 {
                        let mDic = NSMutableDictionary(dictionary: dic2)
                        mDic["weather"] = dic?["weatherStr"]
                        weatherArr.replaceObject(at: i, with: mDic)
                    }
                }
            }
            (weatherArr as NSMutableArray).write(toFile: weatherPath, atomically: true)
        }
        
        // 心情
        let moodPath = docPath + "/mood.plist"
        if let moodArr = NSMutableArray(contentsOfFile: moodPath) {
            for i in 0..<moodArr.count {
                if let dic2 = moodArr[i] as? NSDictionary, let t1 = dic2["timeStamp"] as? String, let t2 = dic?["timeStampStr"] as? String {
                    if t1 == t2 {
                        let mDic = NSMutableDictionary(dictionary: dic2)
                        mDic["mood"] = dic?["moodStr"]
                        moodArr.replaceObject(at: i, with: mDic)
                    }
                }
            }
            (moodArr as NSMutableArray).write(toFile: moodPath, atomically: true)
        }
        
        // 活动
        let activityPath = docPath + "/activity.plist"
        let activityArr = NSMutableArray(contentsOfFile: activityPath) ?? NSMutableArray()
        var index = 0
        while index < activityArr.count {
            if let dic2 = activityArr[index] as? NSDictionary, let t1 = dic2["timeStamp"] as? String, let t2 = dic?["timeStampStr"] as? String {
                if t1 == t2 {
                    activityArr.remove(dic2)
                }
            }
            index += 1
        }
        
        if let arr = dic?["reasonArray"] as? [String], let t = dic?["timeStampStr"] {
            arr.forEach { value in
                let dic2 = ["activity": value, "timeStamp": t]
                activityArr.add(dic2)
            }
        }
        activityArr.write(toFile: activityPath, atomically: true)
        
    }
}
